// src/markdown-it/markdown-image-attributes-plugin.js
import path from "path";

export default function markdownImageAttributesPlugin(md) {
    const defaultRender = md.renderer.rules.html_block || function (tokens, idx, options, env, self) {
        return self.renderToken(tokens, idx, options);
    };

    md.renderer.rules.html_block = function (tokens, idx, options, env, self) {
        let content = tokens[idx].content;

        // Use a regular expression to find all <img> tags and modify their src attribute
        content = content.replace(/<img\s+([^>]*?)src=["']([^"']+)["']/gi, (match, preAttrs, src) => {
            if (!src.startsWith('http') && !src.startsWith('/')) { // Only modify relative paths
                src = path.resolve(options.mdFilePath, src);
                console.log(src)
                src = path.relative("src", src);
                src = `src/${src}`;
            }
            return `<img ${preAttrs}src="${src}"`;
        });

        return content;
    };

    const defaultInlineRender = md.renderer.rules.html_inline || function(tokens, idx, options, env, self) {
        return self.renderToken(tokens, idx, options);
    };

    md.renderer.rules.html_inline = function(tokens, idx, options, env, self) {
        let content = tokens[idx].content;

        // Use a regular expression to find all <img> tags and modify their src attribute
        content = content.replace(/<img\s+([^>]*?)src=["']([^"']+)["']/g, (match ,preAttrs ,src )=>{
            if(!src.startsWith('http')&&!src.startsWith('/')){ // 仅修改相对路径
                console.log("startsWith", src)
                // src=`${basePath}/${src}`;
            }
            return `<img ${preAttrs}src="${src}"`;
        });

        return content;
    };
}
